#!/usr/bin/perl -w

#=========================================================
# access_log_ip
# File ID: b6640aac-5d36-11df-9643-90e6ba3022ac
# Lister ut unike IP'er i access_log
#=========================================================

use strict;
use Socket;

$| = 1;

my %user_ip;
my $total_hits = 0;
my $no_lookup = 0;

defined($ARGV[0]) && ($ARGV[0] eq "-n") && (shift, $no_lookup = 1);

while (<>) {
	if (m!^(\S+)\s+!) {
		$user_ip{$1}++;
		$total_hits++;
	} else {
		warn("Linje $.: Ulovlig format: \"$_\"");
	}
}

my @ip_array = ();

while (my ($us_ip, $us_count) = each %user_ip) {
	push(@ip_array, sprintf("%8u  %15s  (%6.2f%%)  %s", $us_count, $us_ip, ($us_count/$total_hits)*100, ipname($us_ip)));
}

@ip_array = reverse sort @ip_array;

foreach(@ip_array) {
	print("$_\n");
}

if (scalar(@ip_array) == 1) {
	printf("\nTotalt 1 unik IP og 1 treff.\n");
} else {
	printf("\nTotalt %u unike IP'er og $total_hits treff.\n", scalar(@ip_array));
}

sub ipname {
	return("") if ($no_lookup);
	my $i_addr = inet_aton(shift);
	my $Retval = gethostbyaddr($i_addr, AF_INET);
	defined($Retval) || ($Retval = "");
	return $Retval;
} # ipname()

# 193.214.57.46 - - [18/Oct/2001:08:26:44 +0200] "POST / HTTP/1.0" 200 5147 "http://www.ba.no/00/07/12/9.html" "Mozilla/4.03 [en] (WinNT; I)"
# 62.113.158.67 - - [18/Oct/2001:08:26:44 +0200] "POST / HTTP/1.1" 200 15519 "http://basnakk.ba.no/" "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT)"
# 62.113.158.67 - - [18/Oct/2001:08:26:45 +0200] "GET / HTTP/1.1" 200 5137 "-" "Mozilla/4.0 (compatible; MSIE 5.0; Windows 95; DigExt; SenseWave 1.0; IEwebPlus)"
# 193.213.227.243 - - [18/Oct/2001:08:26:45 +0200] "GET / HTTP/1.0" 200 14602 "http://www.ba.no/30/96/38/9.html" "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)"
# 193.217.216.52 - - [18/Oct/2001:08:26:45 +0200] "POST /tabell.php HTTP/1.1" 200 24122 "http://www.nifs.no/tabell.php" "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)"
# 193.213.227.243 - - [18/Oct/2001:08:26:45 +0200] "GET /images/forside/laptop.jpg HTTP/1.0" 200 5347 "-" "Mozilla/3.01 (compatible;)"
# 62.113.158.67 - - [18/Oct/2001:08:26:46 +0200] "POST / HTTP/1.1" 200 15461 "http://basnakk.ba.no/" "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt; SenseWave 1.0)"
# 62.113.158.68 - - [18/Oct/2001:08:26:46 +0200] "POST / HTTP/1.1" 200 17032 "http://basnakk.ba.no/" "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"
# 62.113.158.67 - - [18/Oct/2001:08:26:46 +0200] "GET / HTTP/1.1" 200 5144 "-" "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT)"
# 62.113.158.68 - - [18/Oct/2001:08:26:49 +0200] "POST / HTTP/1.1" 200 16747 "http://basnakk.ba.no/" "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"

#### End of file access_log_ip ####
